from django.db.models import F
from rest_framework import serializers, status

from apps.common.account.models import Account
from apps.prize_system.prize.models import PrizeCategory, PrizeRank, PrizeLevel, Prize, PrizeAuthor, PrizeFile


class PrizeCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = PrizeCategory
        exclude = ('created_time', 'updated_time')


class PrizeRankSerializer(serializers.ModelSerializer):
    class Meta:
        model = PrizeRank
        exclude = ('created_time', 'updated_time')


class PrizeLevelSerializer(serializers.ModelSerializer):
    class Meta:
        model = PrizeLevel
        exclude = ('created_time', 'updated_time')


class PrizeListSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        account_id = self.context.get('account_id', -1)
        ret = super().to_representation(instance)
        ret['prize_category_name'] = instance.prize_category.name
        ret['prize_level_name'] = instance.prize_level.name
        ret['prize_rank_name'] = instance.prize_rank.name

        # 添加作者信息
        all_authors = instance.author.all().values('id', 'sign_order', 'author_type', 'name', 'job_num', 'sex',
                                                   'education', 'job_title', 'faculty_title',
                                                   'contribution_rate', 'faculty_code', 'account_id')
        author_lst = []
        # first_author_lst = []
        for author in all_authors:
            # 署名顺序为1的为第一作者，考虑到多个署名顺序为1的情况
            # if author['sign_order'] == 1:
            #     first_author_lst.append(author['name'])
            # 添加所有作者姓名
            author_lst.append(f"{author['name']}(外)") if author['author_type'].startswith('外') \
                else author_lst.append(author['name'])
        ret['authors'] = all_authors
        # ret['first_author'] = ', '.join(first_author_lst)
        # ret['all_authors'] = ', '.join(author_lst)

        # 添加审核信息, 获取最新的一次一级审核和二级审核的审核意见
        first_check_qs = instance.prize_check.filter(check_level=1).order_by('-created_time').first()
        ret['first_check_opinion'] = first_check_qs.check_opinion if first_check_qs else ''
        second_check_qs = instance.prize_check.filter(check_level=2).order_by('-created_time').first()
        ret['second_check_opinion'] = second_check_qs.check_opinion if second_check_qs else ''


        return ret

    class Meta:
        model = Prize
        fields = '__all__'


class PrizeCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Prize
        fields = '__all__'


class PrizeRetrieve(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)


        # 添加作者信息
        all_authors = instance.author.all().values('id', 'sign_order', 'author_type', 'name', 'job_num', 'sex',
                                                   'education', 'job_title', 'faculty_title',
                                                   'contribution_rate', 'faculty_code', 'account_id')

        for author in all_authors:
            if author['author_type'] != '外校老师' and author['author_type'] != '外校学生':
                account = Account.objects.filter(id=author['account_id']).values('class_title', 'grade_name').first()
                author['class_title'] = account['class_title']
                author['grade_name'] = account['grade_name']
                author['realname'] = author['name']
                author['name'] = author['account_id']
            else:
                author['grade_name'] = None
                author['class_title'] = None

        ret['authors'] = all_authors

        # 添加文件信息
        all_files_obj = instance.files.all()
        # 序列化有请求，文件类型才会返回文件路径带域名
        prize_file_serializer = PrizeFileSerializer(all_files_obj, many=True, context={'request': self.context['request']})
        ret['files'] = prize_file_serializer.data

        # 添加审核历史
        ret['check_history'] = []
        check_qs = instance.prize_check.order_by('-created_time') \
            .only('check_status', 'check_opinion', 'created_time', 'check_level')
        check_level_format = {1: '一级审核', 2: '二级审核'}
        for i in check_qs:
            tmp = {'check_status': i.check_status, 'check_opinion': i.check_opinion,
                   'created_time': i.created_time.strftime('%Y-%m-%d %H:%M'),
                   'check_level_name': check_level_format.get(i.check_level, '审核')}
            ret['check_history'].append(tmp)

        return ret

    class Meta:
        model = Prize
        fields = '__all__'


class PrizeUpdateSerializer(serializers.ModelSerializer):

    def update(self, instance, validated_data):
        # 每次修改都将两个审核改为待审核
        validated_data['first_check_status'] = '待审核'
        validated_data['second_check_status'] = '待审核'
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance

    class Meta:
        model = Prize
        exclude = ('first_check_status', 'second_check_status', 'created_time', 'updated_time')


# class CheckCreateSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = PrizeCheck
#         fields = ('id',)


class AuthorCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = PrizeAuthor
        exclude = ('created_time', 'updated_time')


class AuthorUpdateSerializer(serializers.ModelSerializer):
    job_num = serializers.CharField(allow_blank=True)

    class Meta:
        model = PrizeAuthor
        exclude = ('created_time', 'updated_time', 'prize')


# 一级审核用的序列化类
class FirstCheckListSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['prize_category_name'] = instance.prize_category.name
        ret['prize_level_name'] = instance.prize_level.name
        ret['prize_rank_name'] = instance.prize_rank.name

        # 添加作者信息
        all_authors = instance.author.all().values()
        author_lst = []
        # first_author_lst = []
        for author in all_authors:
            # 署名顺序为1的为第一作者，考虑到多个署名顺序为1的情况
            # if author['sign_order'] == 1:
            #     first_author_lst.append(author['name'])
            # 添加所有作者姓名

            author_lst.append(f"{author['name']}(外)") if author['author_type'].startswith('外') \
                else author_lst.append(author['name'])
        ret['all_authors'] = ', '.join(author_lst)
        ret['authors'] = all_authors
        # ret['first_author'] = ', '.join(first_author_lst)
        # ret['all_authors'] = ', '.join(author_lst)

        return ret

    class Meta:
        model = Prize
        fields = '__all__'


# 二级审核用的序列化类
class SecondCheckListSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['prize_category_name'] = instance.prize_category.name
        ret['prize_level_name'] = instance.prize_level.name
        ret['prize_rank_name'] = instance.prize_rank.name

        # 添加作者信息
        all_authors = instance.author.all().values()
        author_lst = []
        first_author_lst = []
        for author in all_authors:
            # 署名顺序为1的为第一作者，考虑到多个署名顺序为1的情况
            if author['sign_order'] == 1:
                first_author_lst.append(author['name'])
            # 添加所有作者姓名
            author_lst.append(f"{author['name']}(外)") if author['author_type'].startswith('外') \
                else author_lst.append(author['name'])
        ret['first_author'] = ', '.join(first_author_lst)
        ret['all_authors'] = ', '.join(author_lst)

        # 添加一级审核的意见
        check_qs = instance.prize_check.filter(check_level=1).order_by('-created_time').first()
        ret['first_check_opinion'] = check_qs.check_opinion if check_qs else ''

        return ret

    class Meta:
        model = Prize
        fields = '__all__'


class PrizeFileSerializer(serializers.ModelSerializer):

    class Meta:
        model = PrizeFile
        exclude = ('prize', )

